﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class ApiKeyAuthorizeAttribute : Attribute, IActionFilter
{
    private string _requiredApiKey;
    private IConfiguration _configuration;

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // 在这里可以执行操作后的逻辑
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // 在这里执行操作前的逻辑

        // 通过属性注入获取 IConfiguration
        _configuration = (IConfiguration)context.HttpContext.RequestServices.GetService(typeof(IConfiguration));

        // 通过 IConfiguration 读取配置文件中的 API 密钥
        _requiredApiKey = _configuration["APIConfig:ValidApiKey"];

        var providedApiKey = context.HttpContext.Request.Headers["Authorization"];

        if (string.IsNullOrEmpty(providedApiKey) || providedApiKey != _requiredApiKey)
        {
            context.Result = new Microsoft.AspNetCore.Mvc.JsonResult(new { message = "Unauthorized" })
            {
                StatusCode = 401
            };
        }
    }
}
